package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qk.common.PageResult;
import com.qk.dto.activity.ActivityDTO;
import com.qk.entity.Activity;
import com.qk.management.mapper.ActivityMapper;
import com.qk.management.service.ActivityService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @Author: ZgYn
 * @Date 2025/10/9 10:52
 * @name：ActivityServiceImpl
 */
@Slf4j
@Service
public class ActivityServiceImpl implements ActivityService {
    @Autowired
    private ActivityMapper activityMapper;

    @Override
    public PageResult<Activity> getActivities(ActivityDTO activityDTO) {
        PageHelper.startPage(activityDTO.getPage(), activityDTO.getPageSize());
        List<Activity> activities = activityMapper.selectByExample(activityDTO);
        PageInfo<Activity> pageInfo = new PageInfo<>(activities);
        return PageResult.<Activity>builder()
                .total((int) pageInfo.getTotal())
                .rows(activities)
                .build();
    }

    @Override
    public void save(Activity activity) {
        if (ObjectUtils.isEmpty(activity)) {
            throw new RuntimeException("参数错误");
        }
        boolean hasNull = BeanUtil.hasNullField(activity, "id", "voucher", "discount", "createTime", "updateTime");
        if (hasNull) {
            throw new RuntimeException("参数错误");
        }

        activity.setCreateTime(LocalDateTime.now());
        activity.setUpdateTime(LocalDateTime.now());
        activityMapper.insert(activity);
    }

    @Override
    public void delete(Integer id) {
        activityMapper.delete(id);
    }

    @Override
    public Activity getActivity(Integer id) {
        return activityMapper.selectById(id);
    }

    @Override
    public void update(Activity activity) {
        if (ObjectUtils.isEmpty(activity)) {
            throw new RuntimeException("参数错误");
        }
        boolean hasNull = BeanUtil.hasNullField(activity, "id", "voucher", "discount", "createTime", "updateTime");
        if (hasNull) {
            throw new RuntimeException("参数错误");
        }
        activity.setUpdateTime(LocalDateTime.now());
        activityMapper.update(activity);
    }

    @Override
    public List<Activity> getActivitiesByType(Integer type) {
        return activityMapper.selectByType(type);
    }
}
